﻿<template>
    <div class='article-edit'>
        <el-card class='!border-none' shadow='never'>
            <el-page-header :content='$route.meta.title' @back='$router.back()' />
        </el-card>
        <el-card class='mt-4 !border-none' shadow='never'>
            <el-form
                ref='formRef'
                class='ls-form'
                :model='formData'
                label-width='85px'
                :rules='rules'
            >
                <div class='xl:flex'>
                    <div>
                        <el-form-item label='文章类别' prop='type'>
                            <el-select v-model='formData.type' class='w-80'>
                                <el-option
                                    v-for='item in typeList'
                                    :key='item.value'
                                    :label='item.label'
                                    :value='item.value'
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label='地区' prop='city_id'>
                            <el-cascader style='width:280px;' v-model='formData.city_id' :options='cityDataOption'
                            />
                        </el-form-item>
                        <el-form-item label='文章标题' prop='title'>
                            <div class='w-80'>
                                <el-input
                                    v-model='formData.title'
                                    placeholder='请输入文章标题'
                                    type='textarea'
                                    :autosize='{ minRows: 3, maxRows: 3 }'
                                    maxlength='64'
                                    show-word-limit
                                    clearable
                                />
                            </div>
                        </el-form-item>
                        <el-form-item label='文章栏目' prop='cid'>
                            <el-select
                                class='w-80'
                                v-model='formData.cid'
                                placeholder='请选择文章栏目'
                                clearable
                            >
                                <el-option
                                    v-for='item in optionsData.article_cate'
                                    :key='item.id'
                                    :label='item.name'
                                    :value='item.id'
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label='文章简介' prop='desc'>
                            <div class='w-80'>
                                <el-input
                                    v-model='formData.desc'
                                    placeholder='请输入文章简介'
                                    type='textarea'
                                    :autosize='{ minRows: 3, maxRows: 6 }'
                                    :maxlength='200'
                                    show-word-limit
                                    clearable
                                />
                            </div>
                        </el-form-item>
                        <!--            <el-form-item label="摘要" prop="abstract">-->
                        <!--              <div class="w-80">-->
                        <!--                <el-input-->
                        <!--                    type="textarea"-->
                        <!--                    :autosize="{ minRows: 6, maxRows: 6 }"-->
                        <!--                    v-model="formData.abstract"-->
                        <!--                    maxlength="200"-->
                        <!--                    show-word-limit-->
                        <!--                    clearable-->
                        <!--                />-->
                        <!--              </div>-->
                        <!--            </el-form-item>-->
                        <el-form-item label='文章封面' prop='image' v-if='formData.type === 2'>
                            <div>
                                <div>
                                    <material-picker v-model='formData.image' :limit='1' />
                                </div>
                                <div class='form-tips'>建议尺寸：240*180px</div>
                            </div>
                        </el-form-item>

                        <el-form-item label='上传视频' prop='image' v-if='formData.type === 3'>
                            <material-picker type='video' :limit='1' v-model='formData.video' />
                        </el-form-item>

                        <el-form-item label='作者名称' prop='author'>
                            <div class='w-80'>
                                <el-input v-model='formData.author' placeholder='请输入作者名称' />
                            </div>
                        </el-form-item>
                        <el-form-item label='作者头像' prop='image'>
                            <div>
                                <div>
                                    <material-picker v-model='formData.author_img' :limit='1' />
                                </div>
                                <div class='form-tips'>建议尺寸：240*180px</div>
                            </div>
                        </el-form-item>
                        <el-form-item label='排序' prop='sort'>
                            <div>
                                <el-input-number v-model='formData.sort' :min='0' :max='9999' />
                                <div class='form-tips'>默认为0， 数值越大越排前</div>
                            </div>
                        </el-form-item>
                        <el-form-item label='初始浏览量' prop='click_virtual'>
                            <div>
                                <el-input-number v-model='formData.click_virtual' :min='0' />
                            </div>
                        </el-form-item>
                        <!--                        collect_virtual like_virtual-->
                        <el-form-item label='收藏数量' prop='collect_virtual'>
                            <div>
                                <el-input-number v-model='formData.collect_virtual' :min='0' />
                            </div>
                        </el-form-item>
                        <el-form-item label='点赞数量' prop='like_virtual'>
                            <div>
                                <el-input-number v-model='formData.like_virtual' :min='0' />
                            </div>
                        </el-form-item>
                        <el-form-item label='文章状态' required prop='is_show'>
                            <el-radio-group v-model='formData.is_show'>
                                <el-radio :label='1'>显示</el-radio>
                                <el-radio :label='0'>隐藏</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </div>
                    <div class='xl:ml-20' v-if='formData.type !== 3'>
                        <el-form-item label='文章内容' prop='content'>
                            <editor v-model='formData.content' :height='667' :width='620' />
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </el-card>
        <footer-btns>
            <el-button type='primary' :loading='loading' @click='handleSave'>保存</el-button>
        </footer-btns>
    </div>
</template>

<script lang='ts' setup name='articleListsEdit'>
import type { FormInstance } from 'element-plus'
import { useDictOptions } from '@/hooks/useDictOptions'
import { articleAdd, articleCateAll, articleDetail, articleEdit, getCity, getCityNew } from '@/api/article'
import useMultipleTabs from '@/hooks/useMultipleTabs'
import { ref } from 'vue'

const route = useRoute()
const router = useRouter()
const loading = ref(false)

function getFormData(type = 1) {
    return {
        type, // 1文本 2 图文 图文
        id: '',
        title: '',
        image: '',
        cid: '',
        desc: '',
        author_img: '',
        author: '',
        content: '',
        click_virtual: 0,
        sort: 0,
        is_show: 1,
        abstract: '',
        video: '',
        city_id: [],
        collect_virtual: 0,
        like_virtual: 0
        // collect_num: 0,
    }
}

const formData = reactive(getFormData())
const typeList = ref<any>([
    {
        label: '文本',
        value: 1
    },
    {
        label: '图文',
        value: 2
    },
    {
        label: '视频',
        value: 3
    }
])
const cityDataOption = ref([])

async function initCityDataOption() {
    const resp = await getCityNew({})
    if (!resp || !resp.length) return

    function patchMap(v: any) {
        if (!v.hasOwnProperty('children')) return
        if (!v.children || !v.children.length) return
        return v.children.map((item: any) => {
            const { id, name } = item
            const data = {
                value: id, label: name
            }
            const children = patchMap(item)
            if (children) data.children = children
            return data
        })
    }

    cityDataOption.value = resp.map((item: any) => {
        const { id, name } = item
        return {
            label: name, value: id, children: patchMap(item)
        }
    })
    console.log(cityDataOption.value, 'cityData')
}

initCityDataOption()
const { removeTab } = useMultipleTabs()
const formRef = shallowRef<FormInstance>()
const rules = reactive({
    title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
    cid: [{ required: true, message: '请选择文章栏目', trigger: 'blur' }],
    type: [{ required: true, message: '请选择文章类型', trigger: 'blur' }],
    city_id: [{ required: true, message: '请选择地区', trigger: 'blur' }]
})

const getDetails = async () => {
    const data = await articleDetail({
        id: route.query.id
    })
    const whiteList = ['province', 'city_id', 'area']
    Object.keys(formData).forEach((key) => {
        //@ts-ignore
        if (whiteList.includes(key)) return
        formData[key] = data[key]
    })
    const { province, city_id, area } = data
    formData.city_id = [province, city_id, area]
    console.log(formData, 'formData')
}

const { optionsData } = useDictOptions<{
    article_cate: any[]
}>({
    article_cate: {
        api: articleCateAll
    }
})
const cityData = ref<any>([])
initCityData()

async function initCityData() {
    const resp = await getCity()
    cityData.value = resp.map((item: { name: string; id: number }) => {
        const { name, id } = item
        return {
            name,
            id
        }
    })
}

const delay = (time = 300) => {
    return new Promise((resolve: any) => {
        setTimeout(() => {
            resolve()
        }, time)
    })

}

function resetForm() {
    formData.author_img = ''
    formRef.value?.resetFields()
}

const handleSave = async () => {
    if (loading.value) return
    loading.value = true
    console.log(formData.content)
    await formRef.value?.validate()
    await delay(200)
    if (route.query.id) {
        await articleEdit(formData)
        removeTab()
        router.back()
    } else {
        await articleAdd(formData)
        resetForm()
    }
    loading.value = false
}

route.query.id && getDetails()
</script>
